package com.wgc.controller;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.admin.methods.response.NewAccountIdentifier;
import org.web3j.protocol.admin.methods.response.PersonalListAccounts;
import org.web3j.protocol.admin.methods.response.PersonalUnlockAccount;

@RestController
public class AccountController {
	
	@Autowired
	Admin Admin;
	
	@Autowired
	Web3j web3j;

	/**
	 * 创建账号
	 */
	@RequestMapping("/newAccount")
	public void createNewAccount(String password) {
		try {
			NewAccountIdentifier newAccountIdentifier = Admin.personalNewAccount(password).send();
			String address = newAccountIdentifier.getAccountId();
			System.out.println("new account address " + address);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取账号列表
	 */
	@RequestMapping("/accountList")
	public void getAccountList() {
		try {
			PersonalListAccounts personalListAccounts = Admin.personalListAccounts().send();
			List<String> addressList;
			addressList = personalListAccounts.getAccountIds();
			System.out.println("account size " + addressList.size());
			for (String address : addressList) {
				System.out.println(address);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 账号解锁
	 */
	@RequestMapping("/unlockAccount")
	public void unlockAccount(String address, String password) {
		//String address = "0x05f50cd5a97d9b3fec35df3d0c6c8234e6793bdf";
		//String password = "123456789";
		//账号解锁持续时间 单位秒 缺省值300秒
		BigInteger unlockDuration = BigInteger.valueOf(60L);
		try {
			PersonalUnlockAccount personalUnlockAccount = Admin.personalUnlockAccount(address, password, unlockDuration).send();
			Boolean isUnlocked = personalUnlockAccount.accountUnlocked();
			System.out.println("account unlock " + isUnlocked);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
